package cn.com.messageManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.server.Board_Table;
import com.server.PokeServer;
import com.server.thread.ConnectionThread;
import cn.com.broad.Board_seat;
import cn.com.cal.PokeCalVo;
import cn.com.common.Poke;
import cn.com.messageprotocal.MessageProcess;
import cn.com.messageprotocal.ProtocalInterface;
import cn.com.messageprotocal.StateInterface;
import cn.com.user.Poke_User;
import cn.com.usermanage.UserManager;
import cn.com.usermanage.impl.UserManagerImpl;
import cn.com.zhang.Call;
import cn.com.zhang.SellectCard;
import cn.com.zhang.WinObject;
import cn.com.zhang.Zhang;

import java.net.InetAddress;

/**
 * 负责服务端信息发送给客户端信息的组建
 * 在这里根据通信协议，根据server上的变量的变化组件成一个新的消息发送给下一个用户
 * @author zjthinkpad
 */
public class MessageManager implements MessageProcess
{
	private static Logger logger = LoggerFactory.getLogger(MessageManager.class);
	private static mySocket mysocket=new mySocket();
	private boolean on_off=true;
	public static UserManager usermanager = new UserManagerImpl();
	
	/*
	 * 解读客户端发送来的信息，根据具体的信息进行具体的操作
	 */
	public  void parseReceiveMessage(byte[] array,IoSession session,ConnectionThread thread)
	{
		byte[] headerPacket=mysocket.parseHeader(array);	//   解读头信息

		if(headerPacket!=null)
        {
        	int cmd=mysocket.getCmd(headerPacket);
        	int ver=mysocket.getVer(headerPacket);
        	int bodyLen=Math.abs(mysocket.getPackLen(headerPacket));
        	int code=mysocket.getCode(headerPacket);
	        logger.info("收到命令：0x"+Integer.toHexString(cmd));
        	if(on_off)
        	{
	            System.out.println("读头正确");
	        	System.out.println("收到命令：0x"+Integer.toHexString(cmd));
	        	System.out.println("版本号："+ver);
	        	System.out.println("包编码："+code);
	        	System.out.println("包长："+bodyLen);
        	}  
	        byte[] receivePacket=new byte[bodyLen];
	        	//解析包体 
	        receivePacket = mysocket.parseBody(array,bodyLen, code);
        	switch(cmd)
        	{
        		case ProtocalInterface.REQUEST_TABLE:       //登陆请求桌子信息
	    	    	initTableInfo(receivePacket,thread);
					break; 
        		case ProtocalInterface.REQUEST_SEATING :	// 用户请求坐下
        	    	parsInitInfo( receivePacket , session, thread );
        	    	break;	
        		case ProtocalInterface.REQUEST_ZHANG:       //抢庄
        			parseRobZhang( receivePacket , session, thread);
        			break;
        		case ProtocalInterface.CASR_CALL_REQUEST:   //下注响应
        			parseCAll(receivePacket , session, thread);
        			break;
        		case ProtocalInterface.SELE_RESPONSE:       //选牌响应
        			parseSele(receivePacket , session, thread);
        			break;
        		case ProtocalInterface.END_WAITE:
        			parseEndWaite(receivePacket , session, thread);
        			break;
        		//////////////////////////////////////////////////////////	
        	   
        	   
        	    case ProtocalInterface.USER_STAND :	// 用户站起，进行处理
        	    	dealStand(receivePacket,thread);
					    break;
        	    case ProtocalInterface.USER_TALK:
        	    	//解析用户聊天信息
        	    	doUserTalk(receivePacket,thread);
        	    	break;
        	    case ProtocalInterface.USER_BACK_T://请求大厅
        	    	//解析用户返回大厅
        	    	dealUserBack(thread);
        	    	break;
        	    case ProtocalInterface.USER_FACE:        //用户表情
        	    	dealUserFace(receivePacket,thread);
        	    	break;
        	    case ProtocalInterface.REQUEST_ADD_USER: // 用户请求某个用户为牌友
        	    	dealAddFreind(receivePacket,thread);
        	    	break;
        	    case ProtocalInterface.ADD_SUCCESS:     //广播添加好友功
        	    	dealAddSucc(receivePacket,thread);
        	    	break;
        	    case ProtocalInterface.BUY_GIFT:       //购买礼物
        	    	dealBuyGift(receivePacket,thread);
        	    	break;        	     
        	    case ProtocalInterface.REQ_CONNECTION:
        	    	requestReConnection(receivePacket,thread); //   处理用户断线重连的信息
        	    	break;
        	    case ProtocalInterface.RE_VALIDATE_PASS:      //   处理用要求验证密码
        	    	validatePass(receivePacket,thread);
        	    	break;
        	    case ProtocalInterface.REQUEST_ADD_PASS:     //用户请求为房间加锁
        	    	addPass(receivePacket,thread);
        	    	break;
        	    case ProtocalInterface.SEND_MONEY:          //送钱
        	        sendMoney(receivePacket,thread);
        	    	break;
        	    case ProtocalInterface.REQIEST_DO:         //申请扣钱
        	    	 decutMoney(receivePacket,thread);
        	    	break;
        	    default:
        	        break;
        	}
        }
	}
	
	
	/**
	 * 用户登陆
	 * 返回桌子信息
	 * @param receivePacket
	 * @param thread
	 */
	private void  initTableInfo(byte[] receivePacket,ConnectionThread thread)
	{
		Board_Table  table = null;
		Poke_User user = null;
		int readPos = 0;
		
		int userid=mysocket.readInt(receivePacket, readPos);    //用户id
		readPos+=4;
		int tableid = mysocket.readInt(receivePacket, readPos); //  这里得到桌子id
		readPos += 4;
		
		
		synchronized(this)//添加桌子请求同步
		{
			if( PokeServer.tablemap.get( tableid ) == null )
			{
				//如果为空，则初始化这个桌子，加入到map中
				table = MessageManager.usermanager.initTable( tableid ); //  查询数据库，然后得到这个桌子的相关信息
				
				if(table == null)
				{
					connectionFail( thread.getSession(),  StateInterface.NOT_TABLE,"user request table is null.");
					return;
				}
				thread.setTable(table);
				PokeServer.tablemap.put(thread.getTable().getTableId(), thread.getTable());
				table.setBoard_state(1);
			    logger.info("开新桌:"+tableid);
			}
			else
			{
				thread.setTable(PokeServer.tablemap.get(tableid));
				table=PokeServer.tablemap.get(tableid);
			}
		//判断连接是否达到上限
		if(thread.getTable().getMaxconnection() > thread.getTable().getThreadpool().size())
		{
			thread.getTable().getThreadpool().add(thread);
		}else
		{
			connectionFail(thread.getSession(),StateInterface.COUNT_OUT," this table havad reached max connection count.");
			thread.dispose();
			return;
		}
		if(PokeServer.usermap.get( userid ) != null)
		{
			//已登陆
			connectionFail( thread.getSession(),  StateInterface.IS_INING ,userid+" 号 user overlop login .");
			if(thread.getTable().getThreadpool().contains(thread))
			{
				thread.getTable().getThreadpool().remove(thread);
			}
			thread.dispose();
			return;
		}
		else
		{
			try
			{
				//没有这个用户。我就初始化加入服务端的map中
				UserManager manage = new UserManagerImpl();
				user = new Poke_User();
				user.setUser_id( userid );
				//初始化一个用户这里读写数据库，注意优化的地方
				user = manage.initUserInfo( user );
				if(user == null)
				{
					connectionFail( thread.getSession(),StateInterface.NOT_USER,"初始化用户返回为空 initUserInfo ." );
				
					if(thread.getTable().getThreadpool().contains(thread))
					{
						thread.getTable().getThreadpool().remove(thread);
					}
					thread.dispose();
					return;
				}
				
				PokeServer.usermap.put( String.valueOf(user.getUser_id()), user );
				thread.setUser(user);

				//插入关联信息表
				int i = manage.UserLoginSuccess( thread.getTable().getId(), thread.getUser().getUser_id(),thread.getUser().getUser_name(),thread.getUser().getUser_pcture(),thread.getUser().getTotal_momey(),thread.getUser().getSex(),thread.getUser().getHome_add(),thread.getUser().getIs_vip(),(InetAddress.getLocalHost()).getHostAddress().toString(),PokeServer.PORT );
				if(i<1)
				{
					connectionFail( thread.getSession(),StateInterface.OTHER_ERROR,"关联表添加记录失败！！" );	
					if(thread.getTable().getThreadpool().contains(thread))
					{
						thread.getTable().getThreadpool().remove(thread);
					}
					thread.dispose();
					return;
				}
				table.getLooklist().add(user);
			}catch(Exception e)
			{
					e.printStackTrace();
					connectionFail( thread.getSession(),StateInterface.OTHER_ERROR,e.getMessage() );
					if(thread.getTable().getThreadpool().contains(thread))
					{
						thread.getTable().getThreadpool().remove(thread);
					}
					thread.dispose();
					return;
				}
			}
		}
		
        //返回桌子信息
		Vector<Byte> vector =new Vector<Byte>();
		mysocket.writeHeader(ProtocalInterface.RESPONSE_TABLE, (byte)0,(byte)0,vector); // 返回单个桌子的基本信息
		mysocket.writeByte((byte) table.getBoard_state(),vector);	//桌子的状态
        List<Board_seat> seatedlist = this.seatingSeat(thread);     //在桌子上的用户
        int playSize = seatedlist.size();
        int lookSize=table.getLooklist().size();
        int size=playSize+lookSize;
        mysocket.writeByte((byte) size,vector);	  //座位被占用的数量
        
        for(int j=0;j<lookSize;j++)
        {
        	Poke_User tempUser=table.getLooklist().get(j);
        	mysocket.writeInt(tempUser.getUser_id(),vector);//写入用户id
        	mysocket.writeByte((byte)tempUser.getUser_level(),vector);//用户顶级
        	mysocket.writeByte((byte)1, vector);//用户的称谓
        	mysocket.writeByte((byte)10, vector);//用户的坐位号        	
        	mysocket.writeByte((byte)tempUser.getSex_num(), vector);//用户的坐位号
        	mysocket.writeByte((byte)tempUser.getIs_vip(),vector);  //用户vip
        	mysocket.writeInt(tempUser.getExp_value(), vector);     //经验
        	mysocket.writeInt(tempUser.getGift_id(), vector);       //礼物id
        	mysocket.writeFloat(tempUser.getIn_money(),vector);     //买入的钱
        	mysocket.writeFloat(tempUser.getTotal_momey(),vector);       //桌子上还剩的钱
        	logger.info("总资产:"+tempUser.getIn_money());
        	logger.info("买放资产:"+tempUser.getTotal_momey());
//        	mysocket.writeInt(otheruser.getTotal_momey(), vector);   // 	用户的总资产
        	mysocket.writeChiString(tempUser.getUser_name(),vector);
        	mysocket.writeChiString(tempUser.getUser_pcture(),vector);
//        	mysocket.writeChiString(otheruser.getUser_commucity(), vector);
//        	mysocket.writeInt(otheruser.getChar_value(), vector);
//        	mysocket.writeInt(otheruser.getCard_coin(), vector);   
        }
        
        for(int i = 0; i < playSize  ; i++)
        {
        	Board_seat seat = seatedlist.get(i);
        	byte seat_id=(byte)seat.getId();
        	   Poke_User otheruser =null;
        	try
        	{
        		otheruser= (Poke_User)seat.getUserthread().getUser();
        		if(otheruser == null)
        		{
        			logger.info("用户已离开！！");
        			return;
        		}
        	}catch(Exception e)
        	{
        		logger.error("backConnection 中的已经有一个座位失去一个用户");
        		vector.clear();
        		vector = null;
        		return;
        	}
        	
        	mysocket.writeInt(otheruser.getUser_id(),vector);//写入用户id
        	mysocket.writeByte((byte)otheruser.getUser_level(),vector);//用户顶级
        	mysocket.writeByte((byte)1, vector);//用户的称谓
        	mysocket.writeByte(seat_id, vector);//用户的坐位号        	
        	mysocket.writeByte((byte)otheruser.getSex_num(), vector);//用户的坐位号
        	mysocket.writeByte((byte)otheruser.getIs_vip(),vector);  //用户vip
        	mysocket.writeInt(otheruser.getExp_value(), vector);     //经验
        	mysocket.writeInt(otheruser.getGift_id(), vector);       //礼物id
        	mysocket.writeFloat(otheruser.getIn_money(),vector);       //桌子上还剩的钱
        	mysocket.writeFloat(otheruser.getTotal_momey(), vector);   // 	用户的总资产
        	mysocket.writeChiString(otheruser.getUser_name(),vector);
        	mysocket.writeChiString(otheruser.getUser_pcture(),vector);
//        	mysocket.writeChiString(otheruser.getUser_commucity(), vector);
//        	mysocket.writeInt(otheruser.getChar_value(), vector);
//        	mysocket.writeInt(otheruser.getCard_coin(), vector);
        }
        
        switch(table.getBoard_state())
    	{
    		case 1:
    			break;
    		case 2:
    			mysocket.writeByte((byte)table.getRob_now_time(), vector);
    			List<Zhang> len=table.getZhang_reponse();
    			mysocket.writeByte((byte)len.size(), vector);
    			for(byte i=0;i<len.size();i++)
    			{
    				Zhang temp=len.get(i);
    				mysocket.writeByte((byte)temp.getSeatid(), vector);
    				mysocket.writeByte((byte)temp.getIfzhang(), vector);
    			}
    			break;
    		case 3:
    			mysocket.writeByte((byte)table.getCall_now_time(), vector);
    			List<Call> cal=table.getCall_reponse();
    			mysocket.writeByte((byte)cal.size(),vector);
    			for(byte i=0;i<cal.size();i++)
    			{
    				Call tempcall=cal.get(i);
    				mysocket.writeByte((byte)tempcall.getSeatid(),vector);
    				mysocket.writeFloat(tempcall.getCall(),vector);
    			}
    			break;
    		case 4:
    			mysocket.writeByte((byte)table.getSlect_now_time(), vector);
    			List<SellectCard> sele=table.getSele_reponse();
    			mysocket.writeByte((byte)sele.size(),vector);
    			for(byte i=0;i<sele.size();i++)
    			{
    				SellectCard tempsele=sele.get(i);
    				mysocket.writeByte((byte)tempsele.getSeatid(),vector);
    				mysocket.writeByte(tempsele.getNuType(),vector);
    				int[] cardArray=tempsele.getCardArray();
    			    for(byte j=0;j<cardArray.length;j++)
    			    {
    			    	mysocket.writeInt(cardArray[j],vector);
    			    }
    			}
    			break;   
    		case 5:
    			break;
    	}
        mysocket.writeEnd(vector);
        mysocket.writeSend(thread.getSession(),vector);		
        
        castUserLoginSucces(user,thread,table);        
	}
	
	//广播用户登陆成功
	private void castUserLoginSucces(Poke_User user,ConnectionThread thread,Board_Table table)
	{
		Vector<Byte> vector =new Vector<Byte>();
		mysocket.writeHeader(ProtocalInterface.RESPONSE_LOGIN_SUCCESS, (byte)0,(byte)0,vector); // 返回单个桌子的基本信息
		mysocket.writeInt(user.getUser_id(),vector);//写入用户id
    	mysocket.writeByte((byte)user.getUser_level(),vector);//用户顶级
    	mysocket.writeByte((byte)1, vector);//用户的称谓
    	mysocket.writeByte((byte)0, vector);//用户的坐位号        	
    	mysocket.writeByte((byte)user.getSex_num(), vector);//用户的坐位号
    	mysocket.writeByte((byte)user.getIs_vip(),vector);  //用户vip
    	mysocket.writeInt(user.getExp_value(), vector);     //经验
    	mysocket.writeInt(user.getGift_id(), vector);       //礼物id
    	mysocket.writeFloat(user.getIn_money(),vector);       //桌子上还剩的钱
//    	mysocket.writeInt(user.getTotal_momey(), vector);   // 	用户的总资产
    	mysocket.writeChiString(user.getUser_name(),vector);
    	mysocket.writeChiString(user.getUser_pcture(),vector);
//    	mysocket.writeChiString(user.getUser_commucity(), vector);
//    	mysocket.writeInt(user.getChar_value(), vector);
//    	mysocket.writeInt(user.getCard_coin(), vector);
    	mysocket.writeEnd( vector);
        mysocket.CastSend(vector,table);	//广播用户坐下的信息
	}
	
	/**
	 * 登陆异常
	 * @param session
	 * @param falg
	 * @param casea
	 */
	public   void  connectionFail(IoSession session,byte falg,String casea)
	{
			Vector<Byte> vector=new Vector<Byte>();
		    mysocket.writeHeader(ProtocalInterface.LOGIN_EXCEPTION, (byte)0,(byte)0,vector);
	        mysocket.writeByte(falg,vector);	//  连接达到上限
	        mysocket.writeEnd(vector);
	        mysocket.writeSend(session,vector);
	        logger.error("LOGIN_EXCEPTION: case is {}",  casea);
	}
	
	/*
	 * 解读客户端请求坐下信息,并进行初始化的处理
	 *      String  userid    用户ID
	 *      Byte    seatid    坐位ID
	 *      int     in_money  买入的钱	 *      
	 */
	public void parsInitInfo( byte[] bodyarray ,IoSession session, ConnectionThread thread )
	{		
		//读取用户id
		int readPos=0;
		int userid=mysocket.readInt(bodyarray, readPos);
		readPos+=4;
		int tableid=mysocket.readInt(bodyarray, readPos);
		readPos+=4;
		int in_money = mysocket.readInt(bodyarray, readPos); // 带入的钱数
		readPos+=4;
		int seatid = mysocket.readByte( bodyarray, readPos ); // 读取座位id
		readPos += 1;
		Board_Table table = thread.getTable();
			
		Board_seat seat = (Board_seat) table.getPoke_seat().get(seatid-1);		
		logger.info("新用户:"+userid+"带入钱："+in_money+"坐在"+seatid);
		// 加入座位的验证
		if(check_seat(seat,table))
		{
			   Poke_User user1 = PokeServer.usermap.get( String.valueOf(userid));
			   if(user1 == null)
			   {
					seatFail(session,StateInterface.HSA_SEATED);
					return;
			   }
			//这里当桌子为VIP场的时候
//			 if(table.getTable_type().trim().equalsIgnoreCase("3"))
//			 {
//					if(user1.getIs_vip() == 0&& !user1.isIsdecutVIP())
//					{
//						seatFail(session,StateInterface.HSA_SEATED);
//						return;
//					}
//			 }
			
			
			if(in_money>user1.getTotal_momey())
			{
				in_money=user1.getTotal_momey();
			}
			
//			if(user1.getIn_money()>0)
//			{
//				user1.setUser_rest( user1.getIn_money()+user1.getUser_rest() );
//				user1.setIn_money(0);
//			}
//			
//			if(in_money<table.getBuymin())
//			{
//				seatFail(session,StateInterface.HSA_SEATED);
//				return;
//			}
			
			if(thread.getSeat() != null)
			{
				seatFail(session,StateInterface.HSA_SEATED);
				return;
			}
			
			user1.setIn_money(in_money);
			user1.setTotal_momey(user1.getTotal_momey()-in_money);
			
			
			
			try
			{
			    user1 = usermanager.initUser(user1);    //数据库减掉用用户买入的钱,考虑优化
			}catch(Exception e)
			{
				e.printStackTrace();
				logger.error("parsInitInfo  出错:", e.getMessage());
				user1.setTotal_momey(user1.getTotal_momey()+in_money);
				user1.setIn_money(0);
				user1=null;
				seatFail(session,StateInterface.HSA_SEATED);
				return;
			}
			
			thread.setUser(user1);     			//将这个用户和这个线程进行绑定
			seat.setSeating(true);	   			//设置这个座位上已经存在用户
			seat.setUser_id(userid);            //设置用户id
			seat.setUserthread(thread);			//坐位绑定线程  设置该坐位有人了
			thread.setSeat(seat);     			//线程绑定桌子
			session.setAttribute("ownseat", seat);//会话设置坐位
			
			
			int i = usermanager.seatSuccess(seat.getUserthread().getUser().getUser_id());//操作数据库，更改关联表
			if( i<=0 )
			{
				seatFail(session,StateInterface.HSA_SEATED);
				return;
			}
			else
			{
				for(byte j=0;j<table.getLooklist().size();j++)
				{
					if(userid==table.getLooklist().get(j).getUser_id())
					{
						table.getLooklist().remove(j);
					}
				}
				
				castUserSeatSucc(seat,table);	//  广播用户坐下成功
			}
			//table.getActive_list().add(0,seat);
			//房子异常结束标志位没有设置为false
			ifStart(table,thread);
		}else
		{
			seatFail(session,StateInterface.HSA_SEATED);		//坐下失败
		}
	}
	
	/*
	 * 用户坐下失败
	 */
	public void  seatFail(IoSession session,byte type)
	{
		try
		{
		    Vector<Byte> vector=new Vector<Byte>();
		    mysocket.writeHeader(ProtocalInterface.LOGIN_EXCEPTION, (byte)0,(byte)0,vector);
	        mysocket.writeByte(type,vector);	//已经有人
	        mysocket.writeEnd(vector);
	        mysocket.writeSend(session,vector);
		} catch(Exception e)
		{
			e.printStackTrace();
			logger.error("用户坐下失败，返回失败信息出错：{}", e.getMessage());
	    }
	}
	
	/*
	 * 判断这个座位是否已经有人在坐了,有返回false，没有返回true
	 */
	private boolean check_seat(Board_seat seat,Board_Table table)
	{
		if(!seat.isSeating())
		{//没人坐
			seat.setArray(null);
			return true;
		}else
		{//有人坐
			return false;
		}
	}
	
	

	/*
	 * 广播用户坐下成功
	 *byte seat_id;           //座位id
	 *String user_id;        //用户id
	 *金币
	 */
	public void castUserSeatSucc(Board_seat seat,Board_Table table)
	{
		Vector<Byte> vector=new Vector<Byte>();
		Poke_User user=seat.getUserthread().getUser();
        mysocket.writeHeader(ProtocalInterface.CASR_USERSET, (byte)0,(byte)0,vector);
        mysocket.writeInt(user.getUser_id(), vector);  //  用户id
        mysocket.writeByte((byte)seat.getId(), vector);  //  用户座位id
        mysocket.writeInt(user.getIn_money(),vector);    //携带游戏币
        mysocket.writeEnd( vector);
        mysocket.CastSend(vector,table);	//
        logger.info("广播用户坐下的信息");//
	}
	
	//判断是否可以开局
	private boolean ifStart(Board_Table table,ConnectionThread thread)
	{
		if( this.seatingSeat(thread).size()<1)//&&table.isIsplaying()
		{
			//seat.setIf_zhan(true);
			//logger.info("设置庄家"+seat.isIf_zhan());
			table.setIsplaying(false);
			return false;
		}
		else
		{
			table.startup();
		}
		return true;
	}

	
	//收到抢庄信息
	private void parseRobZhang( byte[] bodyarray ,IoSession session, ConnectionThread thread)
	{
		int readPos=0;
		byte seatId=(byte)mysocket.readByte(bodyarray, readPos);
		readPos +=1;
		byte ifZhange = (byte)mysocket.readByte( bodyarray, readPos ); // 读取庄类型　
		readPos += 1;
		
		Board_Table table = thread.getTable();
		
		table.setRobZhang(seatId, ifZhange);
		cast_zhang_do(table,seatId,ifZhange);
		
	}
	
	//收到下注用户信息
	private void parseCAll(byte[] bodyarray ,IoSession session, ConnectionThread thread)
	{
		int readPos=0;
		int user_id=mysocket.readInt(bodyarray, readPos);
		readPos += 4;
		byte seatId=(byte)mysocket.readByte(bodyarray, readPos);
		readPos+=1;
		int money = mysocket.readInt( bodyarray, readPos ); // 所下注
		readPos += 4;
		
		Board_Table table = thread.getTable();
		table.callResponse(seatId, money);
		cast_call_do(table,seatId,money,user_id);
	}
	
	
	/**
	 *       byte seat_id;			//座位id
	 *		 Short pokevalue;	
	 *	     Short pokevalue;	
     * 		 Short pokevalue;			//  用户的牌值  只有显示第三张名牌 暗牌客户
	 * 一次性发完五张牌
	 * @param seat
	 * @param table
	 */
	public void deal_three(Board_seat seat,Board_Table table)
	{
		Vector<Byte> vv = new Vector<Byte>();
		byte seatid = (byte) seat.getId();	// 得到座位id
		mysocket.writeHeader( ProtocalInterface.SEND_CARD, (byte)0,(byte)0,vv );
		mysocket.writeByte( seatid, vv );	// 写入座位id
		logger.info("牌1"+seat.getPokelist().get(0).getFlag());
		logger.info("牌2"+seat.getPokelist().get(1).getFlag());
		logger.info("牌3"+seat.getPokelist().get(2).getFlag());
		logger.info("牌4"+seat.getPokelist().get(3).getFlag());
		logger.info("牌5"+seat.getPokelist().get(4).getFlag());
		
		mysocket.writeShort(seat.getPokelist().get(0).getFlag(), vv);  //  数组下标为0的暗牌 牌值
		mysocket.writeShort(seat.getPokelist().get(1).getFlag(), vv);  //  数组下标为1的暗牌 牌值
		mysocket.writeShort(seat.getPokelist().get(2).getFlag(), vv);
		mysocket.writeShort(seat.getPokelist().get(3).getFlag(), vv);
		mysocket.writeShort(seat.getPokelist().get(4).getFlag(), vv);
	    mysocket.writeEnd( vv );
	    mysocket.writeSend(seat.getUserthread().getSession(), vv );	 
	}
	
	//收到选牌响应
	private void parseSele(byte[] bodyarray ,IoSession session, ConnectionThread thread)
	{
		int readPos=0;
		int seat_id=mysocket.readInt(bodyarray, readPos);
		readPos+=4;
		byte seatId=(byte)mysocket.readByte(bodyarray, readPos);
		readPos+=1;
		int[] pokeArray=new int[5];
		for(int i=0;i<5;i++)
		{
			pokeArray[i] = mysocket.readShort( bodyarray, readPos ); // 所下注
			logger.info("牌值："+pokeArray[i]);
			readPos += 2;
		}
		byte nutype=(byte)mysocket.readByte(bodyarray, readPos);     //牌型 
		Board_Table table = thread.getTable();
		table.checkSelectCard(seatId,pokeArray,nutype);
	}
	
	//收到结算响应
	private void parseEndWaite(byte[] bodyarray ,IoSession session, ConnectionThread thread)
	{
		int readPos=0;
		byte seat_id=(byte)mysocket.readByte(bodyarray, readPos);
		readPos+=1;
		Board_Table table = thread.getTable();
		table.setEndWait(seat_id);
	}
	
	//申请扣钱
	private void decutMoney(byte[] receivePacket, ConnectionThread thread)
	{
		int readPos=0;
		int lenth = mysocket.readShort(receivePacket, readPos);
		readPos +=2;
		String userid = mysocket.readString( receivePacket, lenth,readPos ); //读取用户跟住的钱数
		int user_id = Integer.parseInt(userid);
		int i = usermanager.deductVIP(user_id);		
	}
	
	
	
	public List<Board_seat> seatingSeat(ConnectionThread thread)
	{
		Board_Table table = thread.getTable();
		List<Board_seat> list = table.getPoke_seat();
		List<Board_seat> listarray = new ArrayList<Board_seat>();
		int size = list.size();
		for(int i = 0; i < size;i++)
		{
			if(list.get(i).isSeating())
			{
				listarray.add(list.get(i));
			}
		}
		return listarray;
	}
	
	/*
	 * 连接建立失败，服务端直接返回一个错误信息，然后切断连接
	 */
	public   void  connectionFail( IoSession session)
	{
		Vector<Byte> vector=new Vector<Byte>();
	    mysocket.writeHeader(ProtocalInterface.REQUEST_TABLE_FAIL, (byte)0,(byte)0,vector);
        mysocket.writeByte(StateInterface.COUNT_OUT,vector);	//连接达到上限
        mysocket.writeEnd(vector);
        mysocket.writeSend(session,vector);
	}
	
	
	
	
	/*
	 * 广播用户扣钱信息
	 */
	public void cast_deduct(byte[] array ,Board_Table table)
	{

		Vector<Byte> vv=new Vector<Byte>();
		 mysocket.writeHeader(ProtocalInterface.DEDUCT_FUNDUS, (byte)0,(byte)0,vv);
		mysocket.writeInt(table.getCall_money(), vv);
		mysocket.writeByte((byte)array.length, vv);
		
		for(int i = 0 ;i < array.length;i++)
		{
			mysocket.writeByte(array[i], vv);
			mysocket.writeInt(((Board_seat)(table.getPoke_seat().get(array[i]-1))).getUserthread().getUser().getIn_money(), vv);
			//System.out.println("qqqqqqqqqqqqqqqqqq扣除底钱之后的钱qqqqqqqqqqqqqqqqqqqqq:"+((Board_seat)(table.getPoke_seat().get(array[i]-1))).getUserthread().getUser().getIn_money());
		}
		mysocket.writeEnd(vv);
        mysocket.CastSend(vv,table);
	}
	
	
	/**
	 * 广播游戏结束
	 */
	public void castGameOver(Board_Table table)
	{
		Vector<Byte> vv = new Vector<Byte>();
		mysocket.writeHeader(ProtocalInterface.CAST_GAMEOVER, (byte)0,(byte)0,vv);
		mysocket.writeEnd(vv);
        mysocket.CastSend(vv, table);
	}
	
	
	
	
	/**
	 * 广播用户抢庄
	 */
	public void cast_zhuang(Board_Table table,byte time)
	{
		Vector<Byte> vv = new Vector<Byte>();		
		mysocket.writeHeader( ProtocalInterface.CASR_REQUEST_ZHANG, (byte)0,(byte)0,vv );
		mysocket.writeByte(time, vv);
	    mysocket.writeEnd( vv );
	    mysocket.CastSend( vv ,table);
	}
	
	//广播抢庄操作
	private void cast_zhang_do(Board_Table table,byte seat_id,byte do_type)
	{
		Vector<Byte> vv = new Vector<Byte>();		
		mysocket.writeHeader( ProtocalInterface.CASR_REPONSE_ZHANG, (byte)0,(byte)0,vv );
		mysocket.writeByte(seat_id, vv);
		mysocket.writeByte(do_type, vv);
	    mysocket.writeEnd( vv );
	    mysocket.CastSend( vv ,table);
	}
	
	/**
	 * 广播抢庄结果
	 */
	public void cast_zhang_result(Board_Table table,byte seat_id)
	{
		Vector<Byte> vv = new Vector<Byte>();		
		mysocket.writeHeader( ProtocalInterface.CASR_ZHANG, (byte)0,(byte)0,vv );
		mysocket.writeByte(seat_id, vv);
	    mysocket.writeEnd( vv );
	    mysocket.CastSend( vv ,table);
	}
	
	/**
	 * 广播下注请求
	 */
	public void cast_call(Board_Table table)
	{
		Vector<Byte> vv = new Vector<Byte>();		
		mysocket.writeHeader( ProtocalInterface.CASR_CALL, (byte)0,(byte)0,vv );
		
		List<Board_seat> tempList=table.getActive_list();
		mysocket.writeByte((byte)tempList.size(), vv);
		for(int i=0;i<tempList.size();i++)
		{
			mysocket.writeByte((byte)tempList.get(i).getId(), vv);
		}
	    mysocket.writeEnd( vv );
	    mysocket.CastSend( vv ,table);
	}
	
	//广播用户所下注
	public void cast_call_do(Board_Table table,byte seat_id,int money,int user_id)
	{
		Vector<Byte> vv = new Vector<Byte>();
		mysocket.writeHeader( ProtocalInterface.CASR_RESPONSE_CALL, (byte)0,(byte)0,vv );
		mysocket.writeInt(user_id, vv);
		mysocket.writeByte((byte) seat_id, vv);
		mysocket.writeInt(money, vv);
	    mysocket.writeEnd( vv );
	    mysocket.CastSend( vv ,table);
	}	
	
	/**
	 * 通知选牌
	 */
	public void cast_selet(Board_Table table,byte time)
	{
		Vector<Byte> vv = new Vector<Byte>();		
		mysocket.writeHeader( ProtocalInterface.CASR_SELECT, (byte)0,(byte)0,vv );
		mysocket.writeByte(time, vv);
	    mysocket.writeEnd( vv );
	    mysocket.CastSend( vv ,table);
	}
	/**
	 * 广播选牌动做
	 */
	public void cast_sele_do(Board_Table table,int[] pokeArray, int nuType,byte seat_id,int user_id)
	{
		Vector<Byte> vv = new Vector<Byte>();		
		mysocket.writeHeader( ProtocalInterface.CASR_SELE_DO, (byte)0,(byte)0,vv );
		mysocket.writeInt(user_id, vv);
		mysocket.writeByte(seat_id, vv);
		for(byte i=0;i<pokeArray.length;i++)
		{
			mysocket.writeShort(pokeArray[i], vv);
			logger.info("广播选牌:"+pokeArray[i]);
		}
		mysocket.writeInt(nuType, vv);
	    mysocket.writeEnd( vv );
	    mysocket.CastSend( vv ,table);
	}
	
	/**
	 * 广播结算
	 */
	public void cast_end_settlement(Board_Table table,List<WinObject> winlist)
	{
		Vector<Byte> vv = new Vector<Byte>();		
		mysocket.writeHeader( ProtocalInterface.CASR_COMPARE, (byte)0,(byte)0,vv );
		int len=winlist.size();
		mysocket.writeByte((byte)len,vv);
		
		for(int i=0;i<len;i++)
		{
			WinObject tempWin=new WinObject();
			tempWin=winlist.get(i);
			mysocket.writeInt(tempWin.getUser_id(), vv);
			mysocket.writeByte(tempWin.getSeat_id(),vv);
			int ifzhang=tempWin.isIf_zhang()==true?1:0;
			mysocket.writeByte((byte)ifzhang,vv);
			mysocket.writeFloat(tempWin.getMoney(), vv);
		}
		
	    mysocket.writeEnd( vv );
	    mysocket.CastSend( vv ,table);
	}
	
	/**
	 * 广播用户离开
	 */
	public void cast_userout(Board_seat seat,Board_Table table){
		Vector<Byte> vv = new Vector<Byte>();
		byte seatid = (byte) seat.getId();	// 得到座位id
		mysocket.writeHeader( ProtocalInterface.CAST_USERSETUP, (byte)0,(byte)0,vv );
		mysocket.writeByte( seatid, vv );	// 写入座位id
//		System.out.println("  广播这个座位的用户离开："+seatid);
	    mysocket.writeEnd( vv );
	    mysocket.CastSend( vv ,table);
	    
	}

	
	
	
	/**
	 * 处理用户站起的信息
	 */
	public void dealStand(byte[] bodyarray,ConnectionThread thread){
		int id = 0;
		try{
		int readPos = 0;
		Board_seat seat=null;
		int seatid = mysocket.readByte( bodyarray , readPos ); //读取座位id
		for(int i = 0 ;i < 7;i++)
		{
			if(((Board_seat)(thread.getTable().getPoke_seat().get(i))).getId() == seatid)
			{
				seat = (Board_seat)(thread.getTable().getPoke_seat().get(i));
				seat.setArray(null);
				break;
			}
		}
		id = seatid;
		//	返回用户的钱
		Poke_User user = null;
		try{
			if(seat.getUserthread() != null){
				if(seat.getUserthread().getUser() != null){
					user = seat.getUserthread().getUser();
				}
			}
			if(user == null){
				
				logger.info("用户已经站起，得到的user 为空！");
				return;
			}
		
		}catch(Exception e){
//			System.out.println("用户已经站起");
		logger.info("用户已经站起,得到座位上的用户时出错：{}", e.getMessage());
			return;
		}
//		user.setTotal_momey(user.getIn_money()+ user.getTotal_momey()); //  更新用户的总钱数，告诉客户端，单独发给这个用户
//		user.setIn_money(0);
		thread.getUser().setOut_count(0);
		if(user.getIn_money()>0){
			user.setUser_rest( user.getIn_money()+user.getUser_rest() );
			user.setIn_money(0);
		}
		sendTotalMoney( user.getTotal_momey() + user.getUser_rest() , seat.getUserthread() );  //  告诉客户端自己还有多少钱
		if(seat.getUserthread().getTable().getActive_list().contains(seat))
		{
			seat.getUserthread().getTable().getActive_list().remove(seat);
		}
		seat.setSeating(false);
		usermanager.userStand(user.getUser_id());
		thread.setSeat(null);
		try{
			if(thread !=null ){
			if(thread.getSession() !=null){
				if(thread.getSession().containsAttribute("ownseat")){
					thread.getSession().removeAttribute("ownseat");//解除和座位的帮定
				}
			}
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error("dealStand   解除和座位的绑定出错：{}", e.getMessage());
		}
		seat.setUserthread(null);
		//  首先将用户带入的钱返回到用户的总资产，然后从广播用户站起，单独发送过一条信息给客户单跟新自己的总资产。。。
		//	广播用户站起
		caseUserStand(seat.getId(),thread.getTable());
		
		if( seat != null )
		{
			if( thread.getTable().getActive_list().contains( seat ) )
			{
				thread.getTable().getActive_list().remove( seat );
			}
			seat.resetSeat();
		}	}catch(Exception e){
			//e.printStackTrace();
			caseUserStand(id,thread.getTable());
		}
	}
	
	
	/**
	 * 返回一个总钱数给客户端
	 */
	public void sendTotalMoney(int allmoney,ConnectionThread thread)
	{
		try
		{
			Vector<Byte> vv = new Vector<Byte>();
			mysocket.writeHeader(ProtocalInterface.USER_UPDATE_MONEY, (byte)0,(byte)0,vv);
			mysocket.writeInt(allmoney, vv);
			mysocket.writeEnd(vv);
	        mysocket.writeSend(thread.getSession(), vv);
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 解析用户说话信息，然后广播
	 */
	
	public void doUserTalk(byte[] array,ConnectionThread thread)
	{
		int readPos = 0;
		int len = mysocket.readShort(array, readPos);
		readPos +=2;
		String username = mysocket.readString(array, len, readPos);//用户名
		readPos +=len;
		int len1 = mysocket.readShort(array, readPos);
		readPos +=2;
		String msg = mysocket.readString(array, len1, readPos);  //  用户发送信息
//		System.out.println("用户发送的信息："+msg);
		caseUserTalk(thread.getTable(),msg,username);
	}
	
	/**
	 *广播用户说话 
	 */
	public void caseUserTalk(Board_Table table,String msg,String username){
		Vector<Byte> vv = new Vector<Byte>();
		mysocket.writeHeader( ProtocalInterface.CAST_MESSAGE, (byte)0,(byte)0,vv );
		mysocket.writeChiString(username, vv);  //   发送用户名
		mysocket.writeChiString(msg, vv);// 发送用户说的话
	    mysocket.writeEnd( vv );
	    mysocket.CastSend( vv ,table);
	}
	
	/**
	 * 广播用户站起
	 */
	public void caseUserStand(int seatid,Board_Table table)
	{
		try
		{
			Vector<Byte> vv = new Vector<Byte>();
			mysocket.writeHeader( ProtocalInterface.CASET_USER_STAND, (byte)0,(byte)0,vv );
			mysocket.writeByte((byte) seatid, vv);
		    mysocket.writeEnd( vv );
		    mysocket.CastSend( vv ,table);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 处理用户返回大厅
	 * @param thread
	 */
	public void dealUserBack(ConnectionThread thread)
	{
		casrUserBack(thread);
	}
	
	public void casrUserBack(ConnectionThread conn)
	{
	    conn.dispose();
	}
	//处理用户使用表情
	public void dealUserFace(byte[] array,ConnectionThread thread)
	{
		int readPos = 0;
		int seatid = mysocket.readByte(array, readPos);
		readPos +=1;
		int faceid = mysocket.readByte(array, readPos);
		readPos +=1;
		int money = mysocket.readInt(array, readPos);
		readPos +=4;
		int isvip = mysocket.readByte(array, readPos);
		readPos+=1;
		if(thread.getUser().getIn_money()-money < 0){
			return;
		}
		int aa = thread.getUser().getIn_money()-money;
		thread.getUser().setIn_money(aa);
		/*System.out.println("作为id：。。。。"+seatid);
		System.out.println("表情id：。。。。"+faceid);
		System.out.println("表情消耗的钱：。。。。"+money);
		System.out.println("用户还剩下多少钱：。。。。"+aa);*/
		//广播用户使用了这个表情
		castUseFace(seatid,faceid,aa,thread,(byte)isvip);
	}
	//广播用户使用表情
	public void castUseFace(int seatid,int faceid,int money,ConnectionThread thread,byte isvip)
	{
//		System.out.println("广播用户使用表情。。。。。。。。。");
		Vector<Byte> vv = new Vector<Byte>();
		mysocket.writeHeader( ProtocalInterface.CAST_USER_FACE, (byte)0,(byte)0,vv );
		mysocket.writeByte((byte) seatid, vv);
		mysocket.writeByte((byte) faceid, vv);
		mysocket.writeInt( money, vv);
		mysocket.writeByte(isvip, vv);
	    mysocket.writeEnd( vv );
	    mysocket.CastSend( vv ,thread.getTable());
	}
	
	public void dealAddFreind(byte[] array,ConnectionThread thread)
	{
		int readPos = 0;
		int seatid = mysocket.readByte(array, readPos);
		readPos +=1;
		int friendid = mysocket.readByte(array, readPos);
		readPos +=1;
		castUseWantAdd(seatid,friendid,thread);
	}
	

	public void castUseWantAdd(int seatid,int faceid,ConnectionThread thread)
	{
		Vector<Byte> vv = new Vector<Byte>();
		mysocket.writeHeader( ProtocalInterface.CASE_WANT_ADD, (byte)0,(byte)0,vv );
		mysocket.writeByte((byte) seatid, vv);
		mysocket.writeByte((byte) faceid, vv);
	    mysocket.writeEnd( vv );
	    mysocket.CastSend( vv ,thread.getTable());
	}
	
	public void dealAddSucc(byte[] array,ConnectionThread thread)
	{
		
		int readPos = 0;
		int seatid = mysocket.readByte( array, readPos );
		readPos +=1;
		int friendid = mysocket.readByte( array, readPos );
		readPos +=1;
		castUseAddSucc(seatid,friendid,thread);
	}
	
//	广播用户使用表情
	public void castUseAddSucc(int seatid,int faceid,ConnectionThread thread){
//		System.out.println("广播用户想要添加好友。。。。。。。。。");
		Vector<Byte> vv = new Vector<Byte>();
		mysocket.writeHeader( ProtocalInterface.USER_FR_ADD, (byte)0,(byte)0,vv );
		mysocket.writeByte((byte) seatid, vv);
		mysocket.writeByte((byte) faceid, vv);
		
	    mysocket.writeEnd( vv );
	    mysocket.CastSend( vv ,thread.getTable());
	}
	
	private void dealBuyGift(byte[] receivePacket, ConnectionThread thread) {
		int readPos = 0;
		//座位id
		int seatid = mysocket.readByte(receivePacket, readPos);
		readPos +=1;
		//数组长度
		int arraylenth = mysocket.readByte(receivePacket, readPos);
		readPos +=1;
		byte[] seatlist = new byte[arraylenth];
		for(int i =0;i < arraylenth ;i++ )
		{
			seatlist[i] = (byte) mysocket.readByte(receivePacket, readPos);
			readPos++;
		}
		int cost = mysocket.readInt(receivePacket, readPos);
		readPos+=4;
		int giftid = mysocket.readInt(receivePacket, readPos);
		readPos+=4;
		int strlent = mysocket.readShort(receivePacket, readPos);
		readPos+=2;
		String gifturl = mysocket.readString(receivePacket, strlent, readPos);
		
		int money = thread.getUser().getIn_money()-cost*arraylenth;
		thread.getUser().setIn_money(money);
		castBuyGift((byte)seatid, (byte)arraylenth, seatlist, cost, giftid, gifturl, thread,money);
	}
	
	
	public void castBuyGift(byte seatid,byte arraylenth,byte[] seatlist,int cost,int giftid,String url,ConnectionThread thread,int lemoney)
	{
//		System.out.println("广播用户想要添加好友。。。。。。。。。");
		Vector<Byte> vv = new Vector<Byte>();
		mysocket.writeHeader( ProtocalInterface.CAST_BUY_GIFT, (byte)0,(byte)0,vv );
		mysocket.writeByte((byte) seatid, vv);
		mysocket.writeByte((byte) arraylenth, vv);
		for(int i= 0;i<seatlist.length;i++)
		{
			mysocket.writeByte(seatlist[i], vv);
		}
		mysocket.writeInt(cost, vv);
		mysocket.writeInt(giftid, vv);
		mysocket.writeChiString(url, vv);
		mysocket.writeInt(lemoney, vv);
	    mysocket.writeEnd( vv );
	    mysocket.CastSend( vv ,thread.getTable());
	}
	public static  void sentLip(IoSession session)
	{
		mySocket my = new mySocket();
		Vector<Byte> vv = new Vector<Byte>();
		my.writeHeader( ProtocalInterface.LIP_TOP, (byte)0,(byte)0,vv );
		my.writeByte((byte)1, vv);
		my.writeEnd( vv );
		my.writeSend(session, vv);
		
	}
	
	
	
	
	
	

	//用户请求进行重链接，发给一个用户id，一个桌子id
	public void requestReConnection(byte[] receivePacket, ConnectionThread thread) 
	{
		int readPos=0;
		int stringLen = mysocket.readShort( receivePacket, readPos );
		readPos+=2;
		
		String userid = mysocket.readString( receivePacket, stringLen, readPos );   // 用户id
		 readPos += stringLen;
		int tableid = mysocket.readInt(receivePacket, readPos);
		 readPos += 4;
		dealReConnection(userid,tableid,thread);
	}



	public void dealReConnection(String userid, int tableid, ConnectionThread thread) 
	{
		try
		{
		int user = Integer.parseInt(userid);//  得到用户id 去 map 中取出那个线程
		ConnectionThread th = PokeServer.threadmap.get(user);
		if(th == null)
		{
			System.out.println("th  == null 1");
			//System.out.println(tableid);
			Board_Table table = PokeServer.tablemap.get(tableid);
			if(table ==null){
				reconnectinFail(thread.getSession());
				//如果是table也没有，那么证明是残留用户，从内存中删除，也删除他的数据库
				if(PokeServer.usermap.containsKey(userid)){
					PokeServer.usermap.remove(userid);
				}
				try{
				usermanager.checkUserOut(Integer.parseInt(userid));
				}catch(Exception e){
					e.printStackTrace();
					logger.error("dealReConnection  中删除数据库用户信息出错：{}",e.getMessage());
				}
				return;
			}
			for(int i =0;i<table.getThreadpool().size();i++)
			{
				if(table.getThreadpool().get(i).getUser().getUser_id() == user)
				{
					th = table.getThreadpool().get(i);
					System.out.println("zhao   dao xiancheng");
					break;
				}
			}
			if(th == null)
			{
				System.out.println("th  == null 2");
				if(PokeServer.usermap.containsKey(userid)){
					PokeServer.usermap.remove(userid);
				}
				try{
				usermanager.checkUserOut(Integer.parseInt(userid));
				}catch(Exception e){
					e.printStackTrace();
					logger.error("dealReConnection  中删除数据库用户信息出错：{}",e.getMessage());
				}
				reconnectinFail(thread.getSession());
				return;
			}
			else
			{
				//没有启动等待任务
				if(th.getTask() == null)
				{
					//System.out.println("th.getTask() == null........");
				if(th.getTimer()!=null){
					th.getTimer().cancel();
					th.setTimer(null);
					//System.out.println("th.getTimer().cancel()");
				}
					thread.getSession().removeAttribute("thread");
					if(th.getSession()!=null){
						//System.out.println("连接存在，准备释放关闭．");
						if(th.getSession().containsAttribute("thread")){
							//System.out.println("旧连接存在thread");
							th.getSession().removeAttribute("thread");
						}
						th.getSession().close(true);
					}
					th.setSession(thread.getSession());
					th.getSession().setAttribute("thread", th);
					if(th.getSeat()!=null){
						th.getSession().setAttribute("ownseat", th.getSeat());
					}
					if(thread.getTask()!=null){
						thread.getTask().conn = null;
						thread.setTask(null);
					}
					if(thread.getTimer()!=null){
						thread.setTimer(null);
					}
					thread = null;
					
					//返回应该得到的消息给用户,去map中找到桌子，返回桌子信息，返回用户信息，再返回整个桌子当前信息
					reConnectionTable(th.getSession(),th);
					backReConnection(th.getSession(),th);
				}else{
				
				if(th.getTask().cancel()){	//  取消任务成功，复制线程信息
					//System.out.println("th.getTask().cancel()  is  true");
					try{
						if(th.getTimer()!=null){
							th.getTimer().cancel();	//   定时器取消
							th.setTimer(null);
						}
					
					thread.getSession().removeAttribute("thread");
					if(th.getSession()!=null){
						if(th.getSession().containsAttribute("thread")){
							th.getSession().removeAttribute("thread");
						}
						th.getSession().close(true);
					}
					th.setSession(thread.getSession());
					th.getSession().setAttribute("thread", th);
					if(th.getSeat()!=null){
						th.getSession().setAttribute("ownseat", th.getSeat());
					}
					if(PokeServer.threadmap.containsKey(th.getUser().getUser_id())){
						PokeServer.threadmap.remove( th.getUser().getUser_id() );
					}
					if(thread.getTask()!=null){
						thread.getTask().conn = null;
						thread.setTask(null);
					}
					if(thread.getTimer()!=null){
						thread.setTimer(null);
					}
					thread = null;
					//返回应该得到的消息给用户,去map中找到桌子，返回桌子信息，返回用户信息，再返回整个桌子当前信息
					reConnectionTable(th.getSession(),th);
					
					backReConnection(th.getSession(),th);
					}catch(Exception e){
						e.printStackTrace();
						logger.error("  dealReConnection1  出错：{}", e.getMessage());
						if(thread!=null){
							reconnectinFail(thread.getSession());
							if(thread.getSession()!=null){
								if(thread.getSession().containsAttribute("thread")){
									thread.getSession().removeAttribute("thread");
								}
								thread.getSession().close(true);
							}
						}else if(th.getSession()!=null){
							reconnectinFail(th.getSession());
							if(th.getSession()!=null){
								if(th.getSession().containsAttribute("thread")){
									th.getSession().removeAttribute("thread");
								}
								th.getSession().close(true);
							}
						}
					}
				}else{//取消不成功
					//System.out.println("qu xiao shi bai..."+th.getTask().cancel());
					reconnectinFail(thread.getSession());
					if(thread.getSession()!=null){
						if(thread.getSession().containsAttribute("thread")){
							thread.getSession().removeAttribute("thread");
						}
						thread.getSession().close(true);
					}
					//System.out.println("重连失败：任务取消不成功");
					//th.getTask().run();
				}
				}
			}

		}else{//不为空，那么也就是存在其中，我要取消任务，取消成功则可以进行链接，不成功则只能继续重新登陆
			
			if(th.getTask().cancel()){	//  取消任务成功，复制线程信息
				try{
					if(th.getTimer()!=null){
						th.getTimer().cancel();	//   定时器取消
						th.setTimer(null);
					}
				
				thread.getSession().removeAttribute("thread");
				if(th.getSession()!=null){
					if(th.getSession().containsAttribute("thread")){
						th.getSession().removeAttribute("thread");
					}
				}
				
				
				th.setSession(thread.getSession());
				th.getSession().setAttribute("thread", th);
				if(th.getSeat()!=null){
					th.getSession().setAttribute("ownseat", th.getSeat());
				}
				if(PokeServer.threadmap.containsKey(th.getUser().getUser_id())){
					PokeServer.threadmap.remove( th.getUser().getUser_id() );
				}
				if(thread.getTask()!=null){
					thread.getTask().conn = null;
					thread.setTask(null);
				}
				if(thread.getTimer()!=null){
					thread.setTimer(null);
				}
				thread = null;
				//返回应该得到的消息给用户,去map中找到桌子，返回桌子信息，返回用户信息，再返回整个桌子当前信息
				reConnectionTable(th.getSession(),th);
				
				backReConnection(th.getSession(),th);
				}catch(Exception e){
					e.printStackTrace();
					logger.error("  dealReConnection1  出错：{}", e.getMessage());
					if(thread!=null){
						reconnectinFail(thread.getSession());
						if(thread.getSession()!=null){
							if(thread.getSession().containsAttribute("thread")){
								thread.getSession().removeAttribute("thread");
							}
							thread.getSession().close(true);
						}
					}else if(th.getSession()!=null){
						reconnectinFail(th.getSession());
						if(th.getSession()!=null){
							if(th.getSession().containsAttribute("thread")){
								th.getSession().removeAttribute("thread");
							}
							th.getSession().close(true);
						}
					}
				}
			}else{//取消不成功
				reconnectinFail(thread.getSession());
				if(thread.getSession()!=null){
					if(thread.getSession().containsAttribute("thread")){
						thread.getSession().removeAttribute("thread");
					}
				}
//				System.out.println("重连失败：任务取消不成功");
				//thread.dispose();
				//链接失败
			}
			
		}
		}catch(Exception e)
		{
			e.printStackTrace();
			logger.error("  dealReConnection  出错：{}", e.getMessage());
			if(thread!=null){
				reconnectinFail(thread.getSession());
				if(thread.getSession()!=null){
					if(thread.getSession().containsAttribute("thread")){
						thread.getSession().removeAttribute("thread");
					}
					thread.getSession().close(true);
					
				}
			}
		}
		}
//	返回桌子信息给客户端
	public void backReConnection( IoSession session, ConnectionThread thread )
	{
		try{
			//		写过程
			Vector<Byte> vector=new Vector<Byte>();
			Board_Table table = thread.getTable();
			if(table == null)
			{
        		logger.info("backreConnection 得到thread中的桌子为空！！");
        		return;
        	}
//			如果桌子活动用户小于2，但是桌子的状态为游戏中那么就调整状态位。
			if(table.getActive_list_size()<2&&table.isIsplaying())
			{
				table.setBoard_state(100);
				table.setIsplaying(false);
			}
	        mysocket.writeHeader( ProtocalInterface.RE_CONNECTION, (byte)0,(byte)0,vector );
	        mysocket.writeByte((byte) table.getBoard_state(),vector);	//桌子的状态
	        //System.out.println("。。。桌子的状态："+table.getBoard_state());
	        List<Board_seat> seatedlist = this.seatingSeat(thread);//在桌子上的用户
	        int size = seatedlist.size();
	       // System.out.println("。。。座位被占用的数量："+size);
	        mysocket.writeByte((byte) size,vector);	  //座位被占用的数量
	        //写入现在已经过了多少秒
	        mysocket.writeByte((byte) table.getNowseconds(), vector);
	        //System.out.println("。。。现在过了多少秒："+table.getNowseconds());
	        //总彩池的钱数
//	        mysocket.writeInt(table.getAllmoney(),vector);
	        //System.out.println("。。。总彩池的钱数："+table.getAllmoney());
	        //   桌子上彩池的数量
	        mysocket.writeByte( (byte) table.getGlopool().size(),vector );
	        //System.out.println("。。。桌子上彩池的数量："+table.getGlopool().size());
	        //   每个彩池的钱数
	        for(int i = 0;i < table.getGlopool().size();i++)
	        {
	        	mysocket.writeInt( table.getGlopool().get(i).getMoney() , vector );
	        }
	        
	        for(int i = 0; i < size  ; i++)
	        {
	        	Board_seat seat = seatedlist.get(i);
	        	mysocket.writeByte((byte)seat.getId(),vector);//写入座位id
	        	  // System.out.println("。。。写入座位id："+seat.getId());
	        	   if(seat.getSeat_state() == StateInterface.INIT_STATE)
	        	   {
	        		   mysocket.writeByte((byte) 0, vector);
	        	   }
	        	   else 
	        	   {
	        		   mysocket.writeByte((byte) 1, vector);
	        	   }
	        	   Poke_User otheruser = null;
	        	   try{
	        		   otheruser = (Poke_User)seat.getUserthread().getUser();
	        	if(otheruser == null){
	        		logger.info("backREConnection 得到thread中的 用户 为空！！");
	        		return;
	        	}}catch(Exception e){
	        		logger.error("backREConnection 中座位上的用户已经离开");
	        		vector.clear();
	        		vector = null;
	        		backReConnection(session,thread);
	        		return;
	        		
	        	}
	        	mysocket.writeChiString(String.valueOf(otheruser.getUser_id()),vector);//写入用户id
	        	
	        	  // System.out.println("。。。写入用户id："+(otheruser.getUser_id()));
	        	// 	用户的总资产
	        	mysocket.writeInt(otheruser.getTotal_momey(), vector);
	        	mysocket.writeInt(otheruser.getIn_money(),vector);
	        	//写入座位前面当前彩池的钱数
	        	mysocket.writeInt(seat.getGol_pool(), vector);
	        	mysocket.writeChiString(otheruser.getUser_name(),vector);
	        	mysocket.writeChiString(otheruser.getUser_pcture(),vector);
	        	mysocket.writeByte((byte) otheruser.getIs_vip(), vector);//写入用户是否为VIP
	        	mysocket.writeChiString(otheruser.getUserTitle(), vector);
	        	mysocket.writeChiString(otheruser.getUser_commucity(), vector);
	        	mysocket.writeByte(seat.getSeat_state(),vector);
	        	//用户等级
	        	mysocket.writeByte((byte)otheruser.getUser_level(), vector);
	        	mysocket.writeInt(otheruser.getExp_value(), vector);
	        	mysocket.writeInt(otheruser.getChar_value(), vector);
	        	mysocket.writeInt(otheruser.getCard_coin(), vector);
	        	if(seat.getSeat_state() == StateInterface.INIT_STATE)
	        	{
	        		
	        	}
	        	else
	        	{
	        		if( table.getBoard_state() == 100 )
	        		{
	        		   continue;
	        	    }
//	        		for(int j = 1;j <= table.getBoard_state();j++){
	        		int j = table.getBoard_state();
	        			if(j < 3 )
	        			{
	        				
	        			}else if( j == 7 )
	        			{//发送四章明牌
	        				for(int ii = 0; ii<4;ii++)
	        				{
	        					Poke poke=(Poke)(seat.getPokelist().get(ii+2));
	        					//System.out.println("。。。发到暗牌了："+Integer.toHexString(poke.getFlag()));
	            				mysocket.writeShort(poke.getFlag(), vector);
	        				}
	        				if(otheruser.getUser_id() == thread.getUser().getUser_id())
	        				{//  比对发现是自己，发送第七张暗牌，
		        					//Poke poke=(Poke)(seat.getPokelist().get(6));
		        					//System.out.println("。。。发到暗牌了："+Integer.toHexString(poke.getFlag()));
		            				mysocket.writeShort(((Poke)(seat.getPokelist().get(0))).getFlag(), vector);
		            				mysocket.writeShort(((Poke)(seat.getPokelist().get(1))).getFlag(), vector);
		            				mysocket.writeShort(((Poke)(seat.getPokelist().get(6))).getFlag(), vector);
	        	        	}
	        			}else if(j>7){
	        				//System.out.println("........   打印出j   的 值........."+j);
	        			}else{//发送j-2张明牌
	        				//System.out.println("。。。打印出J的值：：："+j);
	        				for(int iii = 0;iii< j-2;iii++){
	        					//System.out.println("。。。打印出III的值：：：：：："+iii);
	        					Poke poke=(Poke)(seat.getPokelist().get(iii+2));
	        					//System.out.println("。。。还没发到暗牌："+Integer.toHexString(poke.getFlag()));
	            				mysocket.writeShort(poke.getFlag(), vector);
	        				}
	        				if(otheruser.getUser_id() == thread.getUser().getUser_id())
	        				{//  比对发现是自己，发送2张暗牌，
	        					for(int ii = 0; ii<2;ii++)
	        					{
		        					Poke poke=(Poke)(seat.getPokelist().get(ii));
		        					//System.out.println("。。。发到暗牌了："+Integer.toHexString(poke.getFlag()));
		            				mysocket.writeShort(poke.getFlag(), vector);
		        				}
	        	        	}
	        			}
//	        		}
	        	}
	        }
	        mysocket.writeEnd(vector);
	        mysocket.writeSend(session,vector);
			}catch(Exception e){
				e.printStackTrace();
				reconnectinFail(thread.getSession());
				//thread.dispose();
				logger.error("backReConnection 出错：{}", e.getMessage());
				return;
			}
			if(thread.getSeat()!=null){
				//桌子状态
			}
			
	}
	
	
	public void reconnectinFail(IoSession session)
	{
		Vector<Byte> vector=new Vector<Byte>();
	    mysocket.writeHeader(ProtocalInterface.RE_CONNECTION_FAIL, (byte)0,(byte)0,vector);
        mysocket.writeByte((byte)1,vector);//   链接失败，暂时使用这个来代替
        mysocket.writeEnd(vector);
        mysocket.writeSend(session,vector);
	}
	
	
	public void reConnectionTable(IoSession session,ConnectionThread thread)
	{
		Vector<Byte> vv =new Vector<Byte>();
		mysocket.writeHeader(ProtocalInterface.RESPONSE_TABLE, (byte)0,(byte)0,vv); // 返回单个桌子的基本信息
        mysocket.writeChiString(thread.getTable().getTable_name(), vv);
        mysocket.writeInt(thread.getTable().getCall_money(), vv);
        mysocket.writeInt(thread.getTable().getBuymin(), vv);
        mysocket.writeInt(thread.getTable().getBuymax(), vv);
        mysocket.writeInt(thread.getTable().getConsume_money(),vv);
       
        String str = thread.getTable().getTable_type().trim();
        int type = Integer.parseInt(str);
        mysocket.writeByte((byte) type, vv);
        mysocket.writeByte(thread.getTable().getIsClock(), vv);
        mysocket.writeEnd(vv);
        mysocket.writeSend(thread.getSession(),vv);
	}
	
	
	public void validatePass(byte[] bodyarray,ConnectionThread thread ){
		int readPos=0;
		Board_Table table=null;
		int tableid = mysocket.readInt( bodyarray, readPos ); //读取桌子id
		readPos+=4;
		int lent = mysocket.readShort(bodyarray, readPos);
		readPos+=2;
		String pass = mysocket.readString( bodyarray , lent , readPos ); //读取座位id
		readPos += lent;
		table = PokeServer.tablemap.get(tableid);
		if(table == null){//桌子不存在
			System.out.println();
			logger.info("  validatePass   得不到桌子的信息");
			return;
		}else{
			if(table.getPassword().equalsIgnoreCase(pass))
			{
				//验证成功
				reValidatePass(thread.getSession(),thread,(byte)1);
//				System.out.println("验证密码成功！！！！");
			}
			else
			{
				//密码验证错误
				reValidatePass(thread.getSession(),thread,(byte)0);
//				System.out.println("验证密码失败！！！！");
			}
		}
	}
	
	public void reValidatePass(IoSession session,ConnectionThread thread,byte flag)
	{
		Vector<Byte> vv =new Vector<Byte>();
		mysocket.writeHeader(ProtocalInterface.BACK_VALIDATE, (byte)0,(byte)0,vv); // 返回单个桌子的基本信息
		mysocket.writeByte(flag, vv);
        mysocket.writeEnd(vv);
        mysocket.writeSend(thread.getSession(),vv);
	}
	

	public void addPass(byte[] bodyarray, ConnectionThread thread)
	{
		int readPos=0;
		Board_Table table=null;
		
		int lent = mysocket.readShort(bodyarray, readPos);
		readPos+=2;
		String pass = mysocket.readString( bodyarray , lent , readPos ); //读取
		readPos += lent;  //   得到用户加锁的信息
		
		table = thread.getTable();
		if(table.getIsClock() == 1){
			System.out.println("//已经加锁");
			//已经加锁
			reAddPassFail(thread);
			return;
		}else{
			table.setIsClock((byte)1);
			table.setPassword(pass);
			//广播个在座位上面的用户，当前房间被谁加锁，密码是多少
			reAddPass(thread,pass);
//			System.out.println("锁的密码是："+pass);
		}
	}
	//广播房间密码给在坐用户
	public void reAddPass(ConnectionThread thread,String msg)
	{
		Vector<Byte> vv =new Vector<Byte>();
		mysocket.writeHeader(ProtocalInterface.CASE_ADD_PASS, (byte)0,(byte)0,vv); // 返回单个桌子的基本信息
		mysocket.writeChiString( thread.getUser().getUser_name(), vv);
		mysocket.writeChiString(msg, vv);
        mysocket.writeEnd(vv);
        mysocket.CastSendPass(vv,thread.getTable(),thread);
	}

	
	public void reAddPassFail(ConnectionThread thread)
	{
		Vector<Byte> vv =new Vector<Byte>();
		mysocket.writeHeader(ProtocalInterface.ADD_PASS_FAIL, (byte)0,(byte)0,vv); 
		mysocket.writeByte((byte) 1, vv);
		mysocket.writeEnd(vv);
        mysocket.writeSend(thread.getSession(),vv);
	}
	
	//告诉客户端用户返回大厅成功
	public void gotoTingSuss(IoSession session)
	{
		Vector<Byte> vv =new Vector<Byte>();
		mysocket.writeHeader(ProtocalInterface.BACK_TING_SUSS, (byte)0,(byte)0,vv); 
		mysocket.writeByte((byte) 1, vv);
		mysocket.writeEnd(vv);
        mysocket.writeSend(session,vv);
	}
	
	public void clearSeat(Board_Table table,List<Byte> list)
	{
		Vector<Byte> vv = new Vector<Byte>();
		mysocket.writeHeader( ProtocalInterface.CLEAR_SEATS, (byte)0,(byte)0,vv );
		mysocket.writeByte((byte) list.size(), vv);
		for(int i = 0;i < list.size();i++)
		{
			mysocket.writeByte(list.get(i), vv);
		}
	    mysocket.writeEnd( vv );
	    mysocket.CastSend( vv ,table);
		
	}
	
	public void sendMoney(byte[] bodyarray,ConnectionThread thread)
	{
		int readPos=0;
		Board_Table table=null;
		int tableid = mysocket.readInt( bodyarray, readPos ); //读取桌子id
		readPos+=4;
		int myseatid = mysocket.readByte(bodyarray, readPos);
		readPos+=1;
		int friendseatid = mysocket.readByte( bodyarray  , readPos ); //读取座位id
		readPos += 1;
		int money = mysocket.readInt(bodyarray  , readPos );
		table = PokeServer.tablemap.get(tableid);
		Board_seat myseat = table.getBoSeat(myseatid);
		Board_seat friendseat = table.getBoSeat(friendseatid);
		System.out.println("用户送的钱："+money);
		if(table ==null||myseat ==null||friendseat == null||myseat.getUserthread().getUser().getIn_money()<money
				||table.getBig_nate()*20<money||money<=0)
		{
			System.out.println("  。。。。送钱失败！！！");
			sendMoneyFail(thread);
		}else{
			try{
				myseat.getUserthread().getUser().setIn_money(myseat.getUserthread().getUser().getIn_money()-money);
			friendseat.getUserthread().getUser().setIn_money(friendseat.getUserthread().getUser().getIn_money()+money);
			}catch(Exception e){
				sendMoneyFail(thread);
				return;
			}
			castSendSuss(table,myseatid,friendseatid,money);
			Object[] arr = new Object[]{myseat.getUserthread().getUser().getUser_id()+"/"+myseat.getUserthread().getUser().getUser_name(),money,friendseat.getUserthread().getUser().getUser_id()+"/"+friendseat.getUserthread().getUser().getUser_name()};
			logger.info("用户{}送了{}给用户{}",arr);
		}
		
	}
	
	public void sendMoneyFail(ConnectionThread thread)
	{
		Vector<Byte> vv = new Vector<Byte>();
		mysocket.writeHeader( ProtocalInterface.CAST_SEND_MONEY_FAIL, (byte)0,(byte)0,vv );
		mysocket.writeByte((byte) 1, vv);
		mysocket.writeEnd( vv);
	    mysocket.writeSend(thread.getSession(),vv);
	}
	
	public void castSendSuss(Board_Table table,int myseatid,int friendseatid,int money)
	{
		Vector<Byte> vv = new Vector<Byte>();
		mysocket.writeHeader( ProtocalInterface.CAST_SEND_MONEY, (byte)0,(byte)0,vv );
		mysocket.writeByte((byte) myseatid, vv);
		mysocket.writeByte((byte) friendseatid, vv);
		mysocket.writeInt(money, vv);
		mysocket.writeEnd( vv);
		mysocket.CastSend( vv ,table);
	}
}
